package com.wwdx.controller.rest;

import com.wwdx.controller.base.BaseController;
import com.wwdx.model.WvirtualModel;
import com.wwdx.model.WvirtualUserModel;
import com.wwdx.model.WwdxOrderModel;
import com.wwdx.model.WwdxPersonalModel;
import com.wwdx.model.dto.ResultBean;
import com.wwdx.utils.ConstantHolder;
import com.wwdx.utils.math.BigDecimalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Date;
import java.util.SortedMap;

/**
 * @author liguoliang
 */
@RestController
@RequestMapping("virtual")
@ApiIgnore
public class RestVirtualController extends BaseController{

    /**
     * 可购买的虚拟币
     */
    @RequestMapping("/list")
    public ResultBean list() {
        return renderSuccess(wvirtualService.selectModelList(1, 20));
    }

    /**
     * 用户虚拟币查询
     * @param userid 用户ID
     */
    @RequestMapping("/user")
    public ResultBean user(Long userid) {
        WwdxPersonalModel wwdxPersonalModel = wwdxPersonalService.getById(userid);
        BigDecimal bigDecimal = new BigDecimal(0);
        if (wwdxPersonalModel != null){
            WvirtualUserModel wvirtualUserModel = wvirtualUserService.getByUnionId(wwdxPersonalModel.getUnionId());
            if (wvirtualUserModel != null){
                bigDecimal = wvirtualUserModel.getNumber();
            }
        }
        return renderSuccess(bigDecimal);
    }

    /**
     * 虚拟币充值
     * @param orderno 订单号
     * @param productId 产品ID
     * @param type 类型为7则直接购买会员
     */
    @RequestMapping("/recharge")
    public ResultBean recharge(String token, String sign, String orderno, @RequestParam("product_id") Long productId, Integer type) {
        logger.info("虚拟币充值订单号:{}",orderno);
        //过滤非法订单号
        if (!StringUtils.isNumericSpace(orderno)){
            return null;
        }
        SortedMap<String,Object> sortedMap = super.getSortedMap(token,sign);
        sortedMap.put("orderno",orderno);
        sortedMap.put("product_id",productId);
        ResultBean resultBean = super.validSignTokenResult(sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String unionId = (String) resultBean.getData();
        BigDecimal price;
        //会员购买
        if (type == ConstantHolder.Constant.VIPTYPE){
            price = wwdxVipProductService.getByProductId(productId).getPrice();
            payService.vipRecharge(unionId,productId);
            //阅读币充值
        }else {
            WvirtualModel wvirtualModel = wvirtualService.getById(productId);
            if (wvirtualModel == null) {
                String msg = "没有找到虚拟币";
                return renderError(msg);
            }
            price = BigDecimal.valueOf(wvirtualModel.getPrice());
            WvirtualUserModel wvirtualUserModel = wvirtualUserService.getByUnionId(unionId);
            if (wvirtualUserModel == null) {
                wvirtualUserModel = WvirtualUserModel.builder()
                        .createTime(new Date()).unionid(unionId).modifyTime(new Date()).number(price).build();
                wvirtualUserService.save(wvirtualUserModel);
            } else {
                wvirtualUserService.modifyNumber(unionId, price,0);
            }
        }
        //订单记录
        WwdxOrderModel model = WwdxOrderModel.builder()
                .orderno(makeOrderNum()).unionid(unionId).product_id(productId)
                .createTime(new Date()).payTime(new Date()).status(1).price(price)
                .channel(ConstantHolder.Constant.IOS).type(type).payType(ConstantHolder.Constant.VIRTUAL_RECHARGE_PAYTYPE).build();
        wwdxOrderService.save(model);
        return renderSuccess();
    }

    /**
     * 虚拟币购买
     */
    @RequestMapping("/spending")
    public ResultBean spending(Integer userid, Long productId, Integer ptype) {
        WwdxPersonalModel wwdxPersonalModel = wwdxPersonalService.getById((long)userid);
        String unionId = wwdxPersonalModel.getUnionId(),msg;
        //查询产品是否购买
        Integer isorder = wwdxOrderService.isorder(productId, unionId);
        if (isorder == 1){
            msg = "产品已购买";
            return renderError(msg);
        }
        //产品价格
        BigDecimal price;
        switch (ptype){
            //主题包购买
            case ConstantHolder.Constant.THEMETYPE:
                price = wwdxThemeService.getByThemeId(productId).getPrice();
                break;
                //书籍购买 | 小课
            case ConstantHolder.Constant.BOOKTYPE:
            case ConstantHolder.Constant.SMALLBOOKTYPE:
                price = wwdxBookService.getByBookId(productId).getBookprice();
                break;
            default:
                msg = "没有找到商品";
                return renderError(msg);
        }
        //通过优惠卷购买
        price = payService.purchaseCoupon(unionId,price);
        //用户虚拟币数量
        BigDecimal number = wvirtualUserService.getByUnionId(unionId).getNumber();
        //查看用户虚拟币是否充足
        boolean lt = BigDecimalUtils.is(number).lt(price);
        if (lt){
            msg = "虚拟币不足";
            return renderError(msg);
        }
        //扣除虚拟币
        wvirtualUserService.modifyNumber(unionId, price,1);
        //订单记录
        WwdxOrderModel model = WwdxOrderModel.builder()
                .orderno(makeOrderNum()).unionid(unionId).product_id(productId)
                .createTime(new Date()).payTime(new Date()).status(1).price(price)
                .channel(ConstantHolder.Constant.IOS).type(ptype).payType(ConstantHolder.Constant.VIRTUAL_SPENDING_PAYTYPE).build();
        wwdxOrderService.save(model);
        //将已购买数据写入缓存
        taskExecutor.execute(()-> wwdxOrderService.purchase(unionId,productId,ptype));
        return renderSuccess();
    }
}